package com.czk.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.czk.springcloud.entity.CommonResult;
import com.czk.springcloud.entity.Payment;
import com.czk.springcloud.myhandler.CustomBlockHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/12/25 21:42
 */
@RestController
@RequestMapping("/sentinel")
public class RateLimitController {
    /**
     * blockHandler 限流的方法
     *
     * @return
     */
    @GetMapping("/byResource")
    @SentinelResource(value = "byResource", blockHandler = "handlerException")
    public CommonResult byResource() {
        return new CommonResult(200, "按资源名称限流ok", new Payment(2020L, "serial001"));
    }

    /**
     * byResource的兜底方法
     *
     * @param blockException
     * @return
     */
    public CommonResult handlerException(BlockException blockException) {
        return new CommonResult(444, blockException.getClass().getCanonicalName() + "\t 服务不可用");
    }

    /**
     * blockHandlerClass 限流的类
     * blockHandler 限流的类的方法名
     *
     * @return
     */
    @SentinelResource(value = "customBlockHandler", blockHandlerClass = CustomBlockHandler.class, blockHandler = "handlerException2")
    @GetMapping("/customBlockHandler")
    public CommonResult customBlockHandler() {
        return new CommonResult(200, "按客户自定义", new Payment(1994L, "serial003"));
    }
}
